package com.ahdy.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取城市天气
 */
public class getSong {
    public static String getWeather(String city) throws IOException {
        String apiKey = "0bf6e7ae2adf838cac82b4a4f8877f55";
        String apiUrl = "http://apis.juhe.cn/simpleWeather/query";

        HashMap<String, String> map = new HashMap<>();
        map.put("key", apiKey);
        map.put("city", city);

        URL url = new URL(String.format("%s?%s", apiUrl, params(map)));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求头，确保正确处理中文
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // 明确指定UTF-8编码读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream(), StandardCharsets.UTF_8));

        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        connection.disconnect();

        return response.toString();
    }

    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }
}
